package com.huan.study.task.jobs.tasks;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author huan.fu 2021/7/8 - 下午2:46
 */
@Component
@Slf4j
public class DynamicCronTask implements InitializingBean {

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;


    private ScheduledFuture<?> scheduledFuture;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 动态启动一个定时任务
        log.info("注册一个定时任务:每隔1秒执行一次");
        scheduledFuture = register("* * * * * ?");

        // 取消一个调度
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
                log.info("取消调度");
                scheduledFuture.cancel(false);
                log.info("取消结果:" + scheduledFuture.isCancelled());
                log.info("重新注册一个定时任务:每隔2秒执行一次");
                register("*/2 * * * * ?");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private ScheduledFuture<?> register(String cron) {

        // 高版本使用 CronExpression，低版本使用 CronSequenceGenerator
        boolean validExpression = CronExpression.isValidExpression(cron);
        log.info("cron:[{}]是合法的吗:[{}]", cron, validExpression);

        CronExpression expression = CronExpression.parse(cron);
        LocalDateTime nextExecTime = expression.next(LocalDateTime.now());
        if (null != nextExecTime) {
            log.info("定时任务下次执行的时间为:[{}]", nextExecTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }

        return taskScheduler.schedule(new Runnable() {
            @Override
            public void run() {
                log.info("我执行了");
            }
        }, new CronTrigger(cron));
    }
}
